package com.google.code.japndroid;

import android.app.*;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

import java.lang.Thread;
import com.google.code.packetkiller.Utils;
import com.google.code.packetkiller.dao.ConnectionDao;
import com.google.code.packetkiller.dao.DaoFactory;
import com.google.code.packetkiller.preferences.Prefs;

import android.os.SystemClock;
import android.util.Log;
import android.os.RemoteCallbackList;
import android.hardware.Sensor;    // 1.5
import android.hardware.SensorEvent;    // 1.5
import android.hardware.SensorEventListener;    // 1.5
import android.hardware.SensorManager;

public class PacketKillService extends Service {

	public long ACTIVE_INTERVAL = 60 * 1000;
	public AlarmManager manager;
	public PendingIntent pi;
	public Thread t;
	private Intent intent;
	private RemoteCallbackList<IPacketKillCallbackListener> listeners = new RemoteCallbackList<IPacketKillCallbackListener>();
	private int threshold;
	private boolean isDeviceUp = false;
	
	private int debug_val = -1;
	
	private final IPacketKillService.Stub binder = new IPacketKillService.Stub(){

		public boolean start(long _interval,int _pitch) throws RemoteException {
			threshold = _pitch;
			if( intent == null ){
				intent = new Intent();
				intent.setClassName("com.google.code.japndroid","com.google.code.japndroid.PacketKillService");
			}
			intent.setAction("interval");
			intent.putExtra("interval",_interval);
			intent.putExtra("pitch",_pitch);
			
			long interval = _interval * 1000 * 60;
			long firstTime = SystemClock.elapsedRealtime();
			Log.v("PACKET KILLER","CALL RESTART() AlarmManager Set Reating firstTime is " + firstTime +" / interval is " + interval + " ,pitch is " + _pitch);
			
			pi = PendingIntent.getService(PacketKillService.this,0,intent,0);
			manager = (AlarmManager) getSystemService(ALARM_SERVICE);
			manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + interval ,pi);
			
			//manager.cancel(pi);
			//manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime, interval, pi);
			return false;
		}

		public boolean stop() throws RemoteException {
			Log.v("PACKET KILLER","CALL STOP()");
			onDestroy();
			stopSelf();
			return false;
		}
		public boolean hasIntent(){
			return intent != null;
		}
		public void addListener(IPacketKillCallbackListener listener)
				throws RemoteException {
			listeners.register(listener);
			
		}

		public void removeListener(IPacketKillCallbackListener listener)
				throws RemoteException {
			listeners.unregister(listener);
			
		}
		
	};
                                    
	@Override
	public void onStart(Intent intent,int startId){
		this.intent = intent;

        Bundle extras = intent.getExtras();
        long interval = 0;
        if( extras != null ){
        	interval = extras.getLong("interval",0L);
        	threshold = extras.getInt("pitch",0);
        }
        final Prefs prefs = new Prefs(getBaseContext());
		Log.v("PACKET KILLER","OnStart , action is " + intent.getAction() + " and Interval is " + interval);
		if("interval".equals(intent.getAction()) && interval > 1 ){
			t = new Thread(){
			@Override
			public void run(){

				    ConnectionDao connectionDao = DaoFactory.getDao(PacketKillService.this);
					Log.v("PACKET KILLER","I:######### 3G open #########");
					connectionDao.setDataEnabled(true);
			    	//android.os.Vibrator vibrator = (android.os.Vibrator)getSystemService(android.content.Context.VIBRATOR_SERVICE);
			        //vibrator.vibrate(1000);
					statusCallback(true);
					prefs.setLastStatus(true);
					Utils.broadcastStatusChange(getBaseContext(),true);
					try{
						Thread.sleep(ACTIVE_INTERVAL);	
						Log.v("PACKET KILLER","I:######### 3G close after " + ACTIVE_INTERVAL + " /1000 sec #########");
						if( ! isDeviceUp() ) {
							connectionDao.setDataEnabled(false);
							statusCallback(false);
							prefs.setLastStatus(false);
							Utils.broadcastStatusChange(getBaseContext(), false);
							
					        //vibrator.vibrate(1000);
						}
					}catch (InterruptedException e){
						Log.v("PACKET KILLER","I:##### Thread STOPPED ####");
					}
				}
			};
			initSensorManager(sensorEventListener);
			registListener(sensorEventListener);
			try {
				Thread.sleep(1 * 1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			t.start();
			//Toast.makeText(this, "Device up is " + isDeviceUp() + " (threshold:" + threshold + " / current_pitch:"+ debug_val + ")" ,Toast.LENGTH_LONG).show();
			unregistListener(sensorEventListener);	

		}
		try {
			binder.start(interval,threshold);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void statusCallback(boolean isEnabled){
		int num = listeners.beginBroadcast();
		for( int i = 0; i < num ; i++){
			try {
				listeners.getBroadcastItem(i).refresh(isEnabled);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		listeners.finishBroadcast();
	}

	@Override
	public void onCreate(){
		//initSensorManager(sensorEventListener);
	}
	@Override
	public void onDestroy(){
		boolean flg = false;
		if( manager != null  && pi != null){
			manager.cancel(pi);
			flg = true;
		}
		mSensorManager = null;
		Log.v("PACKET KILLER","OnDestroy Stop service and cancel is " + flg);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return binder;
	}
	
	// ========== Orientation Sensor =======
    private SensorManager mSensorManager = null;
	private boolean isDeviceUp() {

		return isDeviceUp;
	}
    private void initSensorManager(SensorEventListener listener){
		Log.v("PACKET KILLER","INIT SENSOR MANAGER");
    	mSensorManager =(SensorManager) getSystemService(SENSOR_SERVICE);
	}
	private void registListener(SensorEventListener listener){
    	// register listener
    	mSensorManager.registerListener(listener,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_FASTEST);
        String s = "REGIST Sonsor Listener";	        
        Log.v("PACKET KILLER",s);
	}
	private void unregistListener(SensorEventListener listener){
	    mSensorManager.unregisterListener(listener);
	}
	private SensorEventListener sensorEventListener = new SensorEventListener(){

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
			
		}

		public void onSensorChanged(SensorEvent event) {
			
	        float azimuth=0,pitch=0,roll=0;

	        azimuth = event.values[SensorManager.DATA_X];
	        pitch = event.values[SensorManager.DATA_Y];
	        roll = event.values[SensorManager.DATA_Z];
		
			int current_pitch = Math.abs((int)pitch);
			debug_val = current_pitch;
			if( threshold > 0 ){ 
				if( current_pitch > threshold) 
					isDeviceUp = true;
				else
					isDeviceUp = false;
			}else{
				isDeviceUp = true;
			}
		}
	};
	
}